package com.bjpowernode.util;

/**
 * Created whit IntelliJ IDEA.
 * Description：
 * User：ZHONGCHEN
 * Date:2022-10-28
 * Time:13:11
 */

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 相关工具类
 */

public class HttpUtils {
    /**
     * 获取HttpURLConnection链接对象
     *
     * @param url 文件地址
     * @return
     */
    public static HttpURLConnection getHttpURLConner(String url) throws IOException {
        URL httpUrl = new URL(url);
        //像文件所在的服务器发送标识信息
        HttpURLConnection urlConnection = (HttpURLConnection) httpUrl.openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.52");
        return urlConnection;
    }

    /**
     * 获取文件名
     *
     * @param url
     * @return
     */
    public static String getHttpFileName(String url) {
        int index = url.lastIndexOf("/");
        return url.substring(index + 1);
    }

    /**
     * 分块下载
     *
     * @param url
     * @param startPos
     * @param endPos
     * @return
     */
    public static HttpURLConnection getHttpURLConner(String url, long startPos, long endPos) throws IOException {
        HttpURLConnection httpURLConnection = getHttpURLConner(url);
        LogUtils.info("下载的区间是:{}-{}", startPos, endPos);
        if (endPos != 0) {
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-" + endPos);
        } else {
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-");
        }
        return httpURLConnection;
    }

    /**
     * 获取文件下载的大小
     *
     * @param url
     * @return
     */
    public static long getHttpFileContentLength(String url) {
        HttpURLConnection httpURLConnection = null;
        int contentLength = 0;
        try {
            httpURLConnection = getHttpURLConner(url);
            contentLength = httpURLConnection.getContentLength();
            httpURLConnection = getHttpURLConner(url);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return contentLength;
    }

}

